﻿// Acknowledge
// This code is mostly taken from below URL
// http://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C

// Copyright (c) DevInstinct Inc. All rights reserved.
// http://devinstinct.com
// Code author: Martin Lapierre
// You cannot remove this copyright and notice.
// This source file is part of the DevInstinct Application Framework.
// You can redistribute the DevInstinct Application Framework in compiled, obfuscated form.
// You cannot redistribute its source files without the written consent of DevInstinct Inc.
// You can freely use and redistribute THIS source file: Singleton.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace uzing
{
    public class uzSingleton<T> where T : class
    {
        private static T _instance;
        private static object _lock = new object();

        private uzSingleton()
        {
        }

        public static T Instance
        {
            get
            {
                if (null == _instance)
                {
                    lock (_lock)
                    {
                        if (null == _instance)
                        {
                            ConstructorInfo constructor = null;
                            try
                            {
                                constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null);
                            }
                            catch (Exception exception)
                            {
                                throw new uzException(exception);
                            }

                            if (null == constructor || constructor.IsAssembly)
                            {
                                throw new uzException(string.Format("A private or " + "protected constructor is missing for '{0}'.", typeof(T).Name));
                            }

                            _instance = (T)constructor.Invoke(null);
                        }
                    }
                }
                return _instance;
            }
        }
    }
}
